# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""

import logging
from optparse import OptionParser

from cve_ease.notifier import MailQQ

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def handle_mailqq(gconfig, db_session, args):
    """[notifier] Notifier of mailqq """
    usage = "usage: %prog mailqq <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-t', '--test', dest='test', action='store_true', default=False,
                      help='run test')
    parser.add_option('-c', '--content', dest='content', default=None,
                      help='test mailqq notifier with specific content')

    (options, args) = parser.parse_args(args)

    if options.test:
        from cve_ease.helper import get_wanip, get_watcher, get_timestamp
        watchers = get_watcher(gconfig)
        notifier_name = "mailqq_notifier"
        for w in watchers:
            cw = watchers[w]
            if notifier_name not in cw:
                continue

            description = ''
            if 'description' in cw:
                description = f"功能描述:\n {cw['description']}"

            def send_mail(key):
                from cve_ease.helper import get_wanip, get_timestamp
                msg = f"Msg from CVE-EASE: \n" \
                      f"发布时间: {get_timestamp()}\n" \
                      f"{notifier_name}测试\n" \
                      f"IP: {get_wanip()}\n" \
                      f"Watcher: {w}\n" \
                      f"{description}"
                if options.content:
                    msg += f"\n附加信息:\n" \
                           f"{options.content}"
                    notifier = MailQQ(gconfig)
                    notifier.send_text(msg, key=key)
                else:
                    notifier = MailQQ(gconfig)
                    notifier.send_text(msg, key=key)

            if len(cw[notifier_name]) >= 3:
                update_notify = cw[notifier_name][:3]
                send_mail(key=update_notify)

            if len(cw[notifier_name]) >= 6:
                status_notify = cw[notifier_name][3:6]
                send_mail(key=status_notify)
            print(f"watcher {w} {notifier_name} send done!")
    else:
        parser.print_help()
